package com.strelitzia.utils;

import com.mysql.cj.util.StringUtils;
import com.strelitzia.constant.RootPath;
import com.strelitzia.entity.ChatContext;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @create 2023/12/16 19:32
 */
public class FileUtil {
    public static String fileUp(MultipartFile document) {
        try {
            File rootPath = ResourceUtils.getFile(RootPath.ROOT_PATH);
            //获取文件名
            String documentName = document.getOriginalFilename();
            //获取文件后缀
            assert documentName != null;
            String hzName = documentName.substring(documentName.lastIndexOf("."));
            //生成文件名
            documentName = UUID.randomUUID().toString().replace("-", "") + hzName;
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String path = rootPath.getPath() + File.separator + format;
            //创建文件夹
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String finalPath = path + File.separator + documentName;
            document.transferTo(new File(finalPath));
            return format + '/' + documentName;
        } catch (IOException e) {
            return "";
        }
    }

    public static List<ChatContext> getChatHistory(Integer userId, Integer friendId) {
        String path;
        if (userId < friendId) {
            path = RootPath.ROOT_PATH + userId + "-" + friendId;
        } else {
            path = RootPath.ROOT_PATH + friendId + "-" + userId;
        }
        File file = new File(path);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return null;
            }
        }
        file = new File(path + "/chat.txt");

        List<ChatContext> chatContexts = new ArrayList<>();
        InputStreamReader reader = null;
        BufferedReader buffer = null;
        try {
            if (file.createNewFile()) {
                System.out.println("文件创建成功！");
            } else {
                System.out.println("文件已存在！");
            }

            reader = new InputStreamReader(Files.newInputStream(file.toPath()));
            buffer = new BufferedReader(reader);
            String line;
            while ((line = buffer.readLine()) != null) {
                if (StringUtils.isNullOrEmpty(line)) {
                    continue;
                }
                ChatContext chatContext = new ChatContext();
                chatContext.setUid(Integer.parseInt(line.split(":")[1]));
                String time = line.split(":")[0];
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMddHHmm"); // 定义输入日期字符串的格式
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 定义输出日期字符串的格式
                Date date = inputFormat.parse(time); // 将输入的日期字符串解析成Date对象
                String formattedDate = outputFormat.format(date); // 将Date对象按指定格式进行格式化
                chatContext.setTime(formattedDate);
                String s = line.substring(line.indexOf(":") + 1);
                chatContext.setContext(s.substring(s.indexOf(":") + 1));
                chatContexts.add(chatContext);
            }
        } catch (IOException | ParseException e) {
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }

            if (buffer != null) {
                try {
                    buffer.close();
                } catch (IOException ignored) {
                }
            }
        }

        return chatContexts;
    }

    public static void saveChatHistory(Integer userId, Integer friendId, ChatContext context) {
        if(context.getContext() ==null || context.getTime() ==null || context.getUid() == null)
            return;
        String path;
        if (userId < friendId) {
            path = RootPath.ROOT_PATH + userId + "-" + friendId;
        } else {
            path = RootPath.ROOT_PATH + friendId + "-" + userId;
        }
        File file = new File(path);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return;
            }
        }
        BufferedWriter writer = null;
        file = new File(path + "/chat.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("文件创建成功！");
            } else {
                System.out.println("文件已存在！");
            }

            writer = new BufferedWriter(new FileWriter(file, true));
            writer.write("\n"+context.getTime()+":" + userId + ":" + context.getContext());

        } catch (IOException ignored) {
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException ignored) {
                }
            }

        }
    }
}
